package com.magupe.develop.wx;

import com.alibaba.fastjson.JSON;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 *
 * </p>
 *
 * @author magp
 * @date 2021/7/27
 */
@RequestMapping("/wx")
@Controller
public class WeChatController {

    /**
     * http://magupe.free.idcfengye.com/web/wx/wxServer
     *
     * @param request
     * @param response
     */
    @RequestMapping(value="/wxServer", method={RequestMethod.GET})
    @ResponseBody
    public void wxServer(HttpServletRequest request, HttpServletResponse response){
        // 1. 获取参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echoStr = request.getParameter("echostr");

        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        System.out.println(echoStr);

        // 2. 服务类配置
        WxMpInMemoryConfigStorage wxConfigProvider = new WxMpInMemoryConfigStorage();
        wxConfigProvider.setToken("ums");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxConfigProvider);

        // 3. 验证token跟微信配置的是否一样
        boolean flag = wxMpService.checkSignature(timestamp, nonce, signature);
        PrintWriter out= null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(flag){
            out.print(echoStr);
        }
        out.close();
    }

    /**
     * 接收消息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/wxServer", produces = {"application/xml;charset=UTF-8;"}, method = {RequestMethod.POST})
    @ResponseBody
    public String receive(HttpServletRequest request, HttpServletResponse response) throws IOException, WxErrorException {
        //获取消息流
        WxMpXmlMessage message = WxMpXmlMessage.fromXml(request.getInputStream());
        System.out.println(JSON.toJSONString(message));
        //消息类型
        String messageType=message.getMsgType();
        if("text".equals(messageType)){
            String res= receiveMsg(message);
            return res;
        }
        else if("event".equals(messageType)){
            String res = receiveMsg(message);
            return  res;
        }
        return "";
    }

    /**
     * 处理消息
     *
     * @param message
     * @return
     */
    public String receiveMsg(WxMpXmlMessage message) throws WxErrorException {
        String str = "";
        String openId = message.getFromUserName();

        // 123

        WxMpInMemoryConfigStorage wxConfigProvider = new WxMpInMemoryConfigStorage();
        wxConfigProvider.setAppId("wxdc74264366806d10");
        wxConfigProvider.setSecret("5b7d08624834dfdfffb357d97694bb8e");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxConfigProvider);
        WxMpUser wxMpUser = wxMpService.userInfo(openId, "zh_CN");
        System.out.println(wxMpUser);

        String toUserName = message.getToUserName();
        String content = message.getContent();
        WxMpXmlOutTextMessage text = WxMpXmlOutTextMessage.TEXT().toUser(openId).fromUser(toUserName).content("hello word, " + content ).build();
        str = text.toXml();
        return str;
    }

    @ResponseBody
    @RequestMapping("/authorize")
    public String authorize(HttpServletRequest request, HttpServletResponse response) throws WxErrorException {
        // 1. 获取请求中的参数
        String code = request.getParameter("code");
        String state = request.getParameter("state");

        // 2. 配置对象 注入微信公众的appid和secret
        WxMpInMemoryConfigStorage wxConfigProvider = new WxMpInMemoryConfigStorage();
        wxConfigProvider.setAppId("wxdc74264366806d10");
        wxConfigProvider.setSecret("5b7d08624834dfdfffb357d97694bb8e");
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxConfigProvider);

        // 3. 返回信息
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
        System.out.println(JSON.toJSONString(wxMpUser));
        System.out.println(JSON.toJSONString(wxMpOAuth2AccessToken));
        return JSON.toJSONString(wxMpUser);
    }
}
